package enterprise.manage.web.controller;

import com.task.offpal.component.validateimg.utils.ValidateImageUtils;
import enterprise.manage.dao.UserDao;
import enterprise.manage.entity.User;
import enterprise.manage.security.LoginHandler;
import enterprise.manage.security.utils.SecurityUtils;
import enterprise.manage.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.DisabledException;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: zhenmingyue
 * Date: 2011-7-4 14:12:21
 * Desc:登陆控制器
 * For :
 */
public class LoginController extends SimpleFormController {
    /**
     * 日志
     */
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

     /**
     * 已登录重定向到首页
     */
    private static final String USERALREADYLOGINEDVIEW = "redirect:/frame.aspx";
    /**
     * 登录成功  logResult的值
     */
    private static final String LOGIN_SUCCESS = "success";
    /**
     * 登录失败  logResult的值
     */
    private static final String LOGIN_FAIL = "fail";
     /**
     * 登录失败允许次数
     */
    private static final Integer LOGIN_FAIL_TIMES = 5;
     /**
     * 登录
     */
    @Autowired
    private LoginHandler loginHandler;
    /**
     * 登录dao
     */
    @Autowired
    private UserDao userDao;
    @Autowired
    private LoginService loginService;
    @Override
    protected Map referenceData(HttpServletRequest httpServletRequest, Object command, Errors errors) throws Exception {
        String userName = httpServletRequest.getParameter("userName");
        httpServletRequest.setAttribute("username", userName);
        return super.referenceData(httpServletRequest, command, errors);
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , Object command, BindException errors) throws Exception {
        LoginCommand loginCommand = (LoginCommand) command;
        httpServletRequest.setAttribute("loginCommand", loginCommand);
        String username = loginCommand.getUsername();
        String password = loginCommand.getPassword();
        httpServletRequest.setAttribute("username", username);
        httpServletRequest.setAttribute("password", password);

        // 验证码校验
        if (!ValidateImageUtils.validate(httpServletRequest)) {
            httpServletRequest.setAttribute("error", "验证码错误");
            return new ModelAndView(getFormView());
        }
        //登录次数限制，半小时内只允许5次失败
        if (loginService.getLoginFailedCount(username) >= LOGIN_FAIL_TIMES) {
            logger.debug("用户名： " + username + " 30分钟内登录失败次数大于等于5次，禁止登录。。。");
            httpServletRequest.setAttribute("error", "很抱歉，您重复登录失败次数过多，请半小时后重新登录...");
            return new ModelAndView(getFormView());
        }
        //验证结束，开始登录
        try {
            loginHandler.login(username, password, httpServletRequest);
        } catch (AuthenticationException authenticationException) {
            //插入登录日志（登录失败）
            loginService.setLoginLog(httpServletRequest.getRemoteAddr(), 0, username,null);
//            if (authenticationException instanceof AuthenticationCredentialsNotFoundException) {
//                httpServletRequest.setAttribute("error", "您输入的用户名" + username + "不存在，请重新输入");
//            } else if (authenticationException instanceof BadCredentialsException) {
//                if (authenticationException.getExtraInformation() != null) {
//                    httpServletRequest.setAttribute("error", "密码错误，请重新输入");
//                } else {
//                    httpServletRequest.setAttribute("error", "您输入的用户名" + username + "不存在，请重新输入");
//                }
//            } else
            if (authenticationException instanceof DisabledException) {
                httpServletRequest.setAttribute("error", "抱歉，此用户名没有激活，请联系管理员激活");
            } else {
                httpServletRequest.setAttribute("error", "抱歉，用户名或密码错误，请重新输入");
            }
            return new ModelAndView(getFormView());
        }
        //插入登录日志（登录成功)
        loginService.setLoginLog(httpServletRequest.getRemoteAddr(), 1, username , SecurityUtils.getUserId(httpServletRequest.getSession()));  

        logger.debug("登录成功，用户名=" + username);
        User user = userDao.getByUserName(username);
        httpServletRequest.getSession().setAttribute(SecurityUtils.SESSION_USER_ID, user.getId());
        httpServletRequest.getSession().setAttribute(SecurityUtils.SESSION_USER_NAME, user.getUserName());
//        httpServletRequest.getSession().setAttribute(SecurityUtils.SESSION_USER, sale);
        return new ModelAndView(USERALREADYLOGINEDVIEW);
    }
}
